package com.amkai.aes.webservice.binary.objecthandler.casehistory;

import java.io.Serializable;
import java.util.Calendar;
import java.util.Date;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Query;

import com.amkai.aes.aescommon.service.binary.job.casehistory.CaseHistoryHelperJob;
import com.amkai.aes.aescommon.service.binary.job.casehistory.CaseHistoryHelperResult;
import com.amkai.aes.generatedbeans.cdmcasehistory.CdmCaseHistory;
import com.amkai.aes.generatedbeans.cdmcasehistory.logdetails.phase.RecoveryDepartmentLog;
import com.amkai.aes.generatedbeans.cdmcasehistory.logdetails.time.TimeLog;
import com.amkai.aes.server.casehistory.CaseHistoryServerUtils;
import com.amkai.aes.server.domaincommiter.casehistory.CaseHistoryLoader;
import com.amkai.aes.server.scheduling.old.SchedulerCdmUtil;
import com.amkai.aes.webservice.binary.JobObjectHandler;
import com.amkai.common.extensions.hibernate.config.SiteManager;
import com.amkai.common.extensions.hibernate.config.manager.SessionManager;

/**
 * #15759 
 */
public class CaseHistoryHelperJobHandler
		implements
		JobObjectHandler<CaseHistoryHelperJob, Serializable, CaseHistoryHelperResult> {

	private static final String CASE_HISTORY_BY_PMCASE = "FROM CdmCaseHistory history WHERE history.pmCase.id = :pmCase";

	private static final Log log = LogFactory
			.getLog(CaseHistoryHelperJobHandler.class);

	private Date calcDate(int field, int amount, Date date) {
		Calendar c = Calendar.getInstance();
		c.setTime(date);
		c.add(field, amount);
		return c.getTime();
	}

	private Date getMaxArrivalTime(CdmCaseHistory history) {
		Date result = null;

		if (history != null) {
			result = calcMaxArrivalTime(history.getAdmissionTimeLog());
			if (result == null) {
				result = calcMaxArrivalTime(history.getPreOpLog()
						.getPhaseTimeLog());
				if (result == null) {
					result = calcMaxArrivalTime(history
							.getOperativeDepartmentLog().getPhaseTimeLog());
				}
			}
		}

		return result;
	}

	private Date calcMaxArrivalTime(TimeLog log) {
		Date result = null;
		if (log != null && log.getBeginTime() != null) {
			result = calcDate(Calendar.MINUTE, -1, log.getBeginTime());
		}
		return result;
	}

	public Date concatDateAndTime(Date date, Date time) {
		if (date != null && time != null) {
			Calendar calDate = Calendar.getInstance();
			calDate.setTime(date);
			Calendar calTime = Calendar.getInstance();
			calTime.setTime(time);
			Calendar calResult = Calendar.getInstance();
			calResult.set(calDate.get(Calendar.YEAR),
					calDate.get(Calendar.MONTH),
					calDate.get(Calendar.DAY_OF_MONTH),
					calTime.get(Calendar.HOUR_OF_DAY),
					calTime.get(Calendar.MINUTE));
			return calResult.getTime();
		}

		return null;
	}

	private Date calcMinDischargeTime(TimeLog log) {
		Date result = null;
		if (log != null && log.getEndTime() != null && log.getEndDate() != null) {
			Date d = concatDateAndTime(log.getEndDate(), log.getEndTime());
			result = calcDate(Calendar.MINUTE, 1, d);
		}
		return result;
	}

	private Date getMinDischargeTime(CdmCaseHistory history, SessionManager sm) {
		Date result = null;

		if (history != null) {
			RecoveryDepartmentLog rc = CaseHistoryServerUtils.getTopRecoveryDepartmentLog(sm, history);
			//#16503 this value can be null
			if (rc != null)
				result = calcMinDischargeTime(rc.getPhaseTimeLog());
			if (result == null) {
				result = calcMinDischargeTime(history.getStepDownLog()
						.getPhaseTimeLog());
				if (result == null) {
					result = calcMinDischargeTime(history.getPacuLog()
							.getPhaseTimeLog());
					if (result == null) {
						result = calcMinDischargeTime(history
								.getOperativeDepartmentLog().getPhaseTimeLog());
					}
				}
			}
		}

		return result;
	}

	@Override
	public CaseHistoryHelperResult process(CaseHistoryHelperJob job,
			Serializable object) throws Exception {
		CaseHistoryHelperResult result = new CaseHistoryHelperResult();

		if (job.getJobKind() != null) {

			SessionManager sm = SiteManager.Start();
			sm.openSession();
			try {

				switch (job.getJobKind()) {
				case DOWNLOAD:
					if (job.getCaseId() != null) {

						Query query = sm.execute(CASE_HISTORY_BY_PMCASE);
						query.setParameter("pmCase", job.getCaseId());

						CdmCaseHistory history = (CdmCaseHistory) query
								.uniqueResult();
						if (history != null) {
							CaseHistoryLoader caseHistoryLoader = new CaseHistoryLoader();
							history = caseHistoryLoader.load(sm, history);

							result.setCaseHistory(history);
							result.setMaxArrivalTime(getMaxArrivalTime(history));
							result.setMinDischargeTime(getMinDischargeTime(
									history, sm));
						}
					}
					break;

				case UPDATE:
					SchedulerCdmUtil.update(sm, job.getCaseHistory(), job.getArrivalTime(),
							job.getDischargeTime(), true);
					break;
				}

			} finally {
				sm.closeSession();
			}
		}

		return result;
	}

	
	

}
